package com.yuanzong.wuliu.service.app.auth;

import com.yuanzong.wuliu.common.exception.BusinessException;
import com.yuanzong.wuliu.common.utils.code.PhotoCodeUtils;
import com.yuanzong.wuliu.common.utils.password.MD5Utils;
import com.yuanzong.wuliu.common.vo.ApiResult;
import com.yuanzong.wuliu.controller.app.auth.param.AppAuthLoginParam;
import com.yuanzong.wuliu.controller.intercdeptor.AdminHandlerInterceptorAdapter;
import com.yuanzong.wuliu.controller.intercdeptor.AppHandlerInterceptorAdapter;
import com.yuanzong.wuliu.model.business.customer.BusinessCustomer;
import com.yuanzong.wuliu.service.business.customer.factory.BusinessCustomerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AppAuthService {

    public ApiResult login(AppAuthLoginParam param) throws Exception {
        // ===================================================================================//
        // ===== 参数校验
        // ===================================================================================//
        if (param == null) {
            throw new BusinessException("参数为空");
        }
        if (!param.getPhotoCode().equals(PhotoCodeUtils.photoCodeMap.get(param.getPhotoCodeKey()))) {
            throw new BusinessException("图片验证码错误");
        }
        BusinessCustomer businessCustomer = BusinessCustomerFactory.getBusinessCustomerService().queryByPhone(param.getPhone());
        if (businessCustomer == null) {
            throw new BusinessException("客户不存在");
        }
        // ===================================================================================//
        // ===== 业务执行
        // ===================================================================================//
        // 生成Token
        String token = MD5Utils.MD5(System.currentTimeMillis() + "");
        AppHandlerInterceptorAdapter.setRuntimeUser(token, businessCustomer.getId());
        // 返回内容
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        resultMap.put("businessCustomer", businessCustomer);
        return ApiResult.success(resultMap);
    }
}
